<script setup lang="ts" name="userHome">
import {nextTick, onMounted, ref, watch} from "vue";
import {useStore} from "vuex";
import {queryLog, signin, user_info, modify_info, qqUnbind} from "@/api/user.ts"
import {Notice, Modal, Message} from "view-ui-plus";
import {usePage} from "@/plugins/pagination";
import {qqBindBackUrl} from "@/plugins/config.ts";
import {AUTHORITY} from "@/utils/dict.ts";

declare const QC;

const store = useStore();
let pagination = usePage();
let USER_INFO = ref<any>(store.getters.getUserData);

let logList = ref([]);// 日志列表
let logAllList = ref<any>([]);// 日志全部列表
let showModal = ref(false);// 修改个人信息弹窗
let showLog = ref(false);// 日志弹窗
let logLoading = ref(false);// 日志弹窗loading
let loading = ref(false);// 修改信息弹窗loading

let signStatus = ref(true);// 是否签到
let formElement = ref();
let formValidate = ref({
  name: '',
  username: '',
  intro: '',
  sex: '',
  qq: '',
  tel: '',
  APPID: '',
  email: ''
});
let ruleValidate = ref({
  name: [
    {required: true, message: '请输入昵称', trigger: 'change'}
  ],
  username: [
    {required: true, message: '请输入用户名', trigger: 'change'}
  ],
  sex: [
    {required: false, message: '请选择性别', trigger: 'change'}
  ],
  qq: [
    {required: false, message: '请输入qq号', trigger: 'change'}
  ],
  tel: [
    {required: false, message: '请输入手机号', trigger: 'change'}
  ],
  intro: [
    {required: false, message: '请输入个人简介', trigger: 'change'}
  ]
});


watch(showLog, (e) => {
  console.log(e)
  if (e) {
    getAllLog()
  }
})

const onOk = () => {
  // 点击保存
  formElement.value?.validate((valid) => {
    if (valid) {
      loading.value = true;
      modify_info(formValidate.value).then((result: any) => {
        loading.value = false;
        if (result.code == 200) {
          Notice.success({
            title: result.data
          });
          getUserInfo();
          showModal.value = false;
        } else {
          Notice.warning({
            title: result.data
          });
        }
      }).catch((error: any) => {
        loading.value = false;
      })
    } else {
      Message.warning("请认真检查表单完整性")
    }
  })
}

const openEdit = () => {
  formValidate.value = JSON.parse(JSON.stringify(USER_INFO.value));
  showModal.value = true;
}

const signIn = () => {
  // 签到
  signin().then((res: any) => {
    console.log(res)
    if (res.code == 200) {
      signStatus.value = false;
      Notice.success({
        title: res.data
      });
    } else {
      signStatus.value = true;
      Notice.warning({
        title: res.data
      });
    }
    getQueryLog()
  })
}


const isSignIn = () => {
  // 判断是否签到
  signin({date: Date.now()}).then((res: any) => {
    console.log(res)
    if (res.code == 200) {
      signStatus.value = true;
    } else {
      signStatus.value = false;
    }
  })
}
const getQueryLog = () => {
  // 查询用户的操作日志
  queryLog({
    pageSize: 5,
    pageNo: 1
  }).then(result => {
    console.log(result)
    logList.value = result.data.data;
  })
}
const getAllLog = () => {
  // 查询用户的全部日志
  logLoading.value = false;
  queryLog(pagination).then(result => {
    console.log(result)
    pagination.total = result.data.total;
    logAllList.value = result.data.data;
    nextTick(() => {
      logLoading.value = true;
    })
  })
}

const bindQQ = () => {
  // 绑定QQ
  const qqLoginUrl = 'https://graph.qq.com/oauth2.0/authorize?client_id=' + QC.getAppId() + '&response_type=token&redirect_uri=' + qqBindBackUrl
  location.href = qqLoginUrl;
}

const getUserInfo = () => {
  // 获取用户个人信息
  user_info().then(res => {
    USER_INFO.value = res.data;
    store.dispatch('UpdateLoginStatus', {
      UserData: res.data
    })
  })
}

const unbindQQ = () => {
  // QQ解除绑定
  Modal.confirm({
    title: '提醒',
    content: '<p>确认要解除当前绑定的QQ吗</p>',
    onOk: () => {
      qqUnbind().then((result: any) => {
        if (result.code == 200) {
          Message.success(result.data)
          showModal.value = false;
          getUserInfo();
        } else {
          Message.error(result.data)
        }
      })
    }
  });
}

onMounted(() => {
  getUserInfo()
  getQueryLog()
  isSignIn()
})
</script>

<template>
  <div class="userHome">
    <div class="userInfo">
      <div class="userAvatar">
        <div class="avatar">
          <Avatar class="avatar" :src="USER_INFO.outimg"/>
          <div class="updateImg">更换头像</div>
        </div>
        <div class="userAuthor">
          <b>{{ USER_INFO.name }}</b>
          <Tag style="width: fit-content;" :color="USER_INFO.authority == AUTHORITY.etc ? 'primary' : '#f6cf7e'">
            {{ AUTHORITY[USER_INFO.authority] }}
          </Tag>
        </div>
        <div class="editBtn">
          <Button size="default" type="primary" style="margin-right: 10px" icon="md-calendar" :disabled="!signStatus"
                  @click="signIn">
            {{ signStatus ? '签到' : '已签到' }}
          </Button>
          <Button size="default" icon="ios-create-outline" @click="openEdit">编辑资料</Button>
        </div>
      </div>
    </div>
    <div class="editInfo">
      <Row>
        <Col :span="4">ID</Col>
        <Col :span="4">{{ USER_INFO.user_id }}</Col>
        <Col :span="4">用户名</Col>
        <Col :span="4">{{ USER_INFO.username || '无' }}</Col>
        <Col :span="4">性别</Col>
        <Col :span="4">{{ USER_INFO.sex || '未知' }}</Col>
      </Row>
      <Row>
        <Col :span="4">是否绑定QQ</Col>
        <Col :span="4">{{ USER_INFO.APPID ? '是' : '否' }}</Col>
        <Col :span="4">openid</Col>
        <Col :span="12">{{ USER_INFO.APPID || '未绑定' }}</Col>
      </Row>
      <Row>
        <Col :span="4">QQ</Col>
        <Col :span="4">{{ USER_INFO.qq }}</Col>
        <Col :span="4">绑定邮箱</Col>
        <Col :span="12">{{ USER_INFO.email || "未绑定" }}</Col>
      </Row>
      <Row>
        <Col :span="4">手机号</Col>
        <Col :span="4">{{ USER_INFO.tel }}</Col>
        <Col :span="4">注册时间</Col>
        <Col :span="12">{{ USER_INFO.create_time }}</Col>
      </Row>
      <Row>
        <Col :span="4">积分</Col>
        <Col :span="4">{{ USER_INFO.gold }}</Col>
        <Col :span="4">账号状态</Col>
        <Col :span="12">{{ USER_INFO.user_status == "1" ? "正常" : "冻结" }}</Col>
      </Row>
      <Row>
        <Col :span="4">个人介绍</Col>
        <Col :span="20">{{ USER_INFO.intro }}</Col>
      </Row>
    </div>
    <Typography>
      <blockquote>操作日志</blockquote>
    </Typography>
    <Timeline pending>
      <TimelineItem v-for="(item,index) in logList" :key="index">
        <p class="time">{{ item.create_time + " " + item.title }}</p>
        <p class="content">{{ item.content }}</p>
      </TimelineItem>
      <TimelineItem><a @click="showLog=true">查看更多</a></TimelineItem>
    </Timeline>
  </div>
  <Modal
      width="40%"
      ok-text="保存"
      v-model="showModal"
      :closable="false"
      :mask-closable="false"
      title="编辑资料">
    <template #footer>
      <Space :size="20">
        <a @click="showModal=false">取消</a>
        <Button @click="onOk" type="primary" :loading="loading">保存</Button>
      </Space>
    </template>
    <Form ref="formElement" :model="formValidate" :rules="ruleValidate" :label-width="80">
      <FormItem label="用户名" prop="username">
        <Input v-model="formValidate.username" placeholder=""></Input>
      </FormItem>
      <FormItem label="昵称" prop="name">
        <Input v-model="formValidate.name" placeholder=""></Input>
      </FormItem>
      <FormItem label="性别" prop="sex">
        <RadioGroup v-model="formValidate.sex">
          <Radio label="男">男</Radio>
          <Radio label="女">女</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="手机号" prop="tel">
        <Input v-model="formValidate.tel" placeholder=""></Input>
      </FormItem>
      <FormItem label="QQ" prop="qq">
        <Input v-model="formValidate.qq" placeholder=""></Input>
      </FormItem>
      <FormItem label="邮箱" prop="email">
        <span>{{ formValidate.email }}</span>
      </FormItem>
      <FormItem label="绑定QQ" prop="bindQQ">
        <div v-if="formValidate.APPID">
          <Poptip placement="right-end" trigger="hover" title="openid" :content="formValidate.APPID">
            <a>已绑定</a>
          </Poptip>
          <a @click="unbindQQ" style="margin-left: 20px;color:#ff0000;">解除绑定</a>
        </div>
        <Button @click="bindQQ" v-else>绑定QQ</Button>
      </FormItem>
      <FormItem label="个人简介" prop="intro">
        <Input v-model="formValidate.intro" type="textarea" :autosize="{minRows: 3,maxRows: 7}"
               placeholder="Enter something..."></Input>
      </FormItem>
    </Form>
  </Modal>
  <Modal :width="50" title="全部日志" v-model="showLog">
    <div v-if="logLoading">
      <Timeline pending>
        <TimelineItem v-for="(item,index) in logAllList" :key="index">
          <p class="time">{{ item.create_time + " " + item.title }}</p>
          <p class="content">{{ item.content }}</p>
        </TimelineItem>
      </Timeline>
      <Page style="margin-top: 10px;" :modelValue="pagination.pageNo" :total="pagination.total" @on-change="(e) => {pagination.pageNo = e;getAllLog()}"
             show-total show-elevator/>
    </div>
  </Modal>
</template>

<style scoped lang="scss">
.userHome {
  padding: 20px;
  background-color: #fff;

  .userInfo {
    .userAvatar {
      border-bottom: 1px solid #ddd;
      padding-bottom: 20px;
      display: flex;

      .avatar {
        width: 80px;
        height: 80px;
        vertical-align: top;
        position: relative;

        .updateImg {
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;
          right: 0;
          background-color: transparent;
          color: transparent;
          cursor: pointer;
          user-select: none;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all .2s;
          border-radius: 50%;

          &:hover {
            background-color: rgba(0, 0, 0, .5);
            color: #fff;
          }
        }
      }

      .userAuthor {
        display: flex;
        flex-direction: column;
        margin-left: 20px;

        > b {
          font-size: 25px;
        }
      }

      .editBtn {
        margin-left: auto;
      }

    }
  }

  .editInfo {
    // 查看并修改信息
    margin-top: 20px;

    :deep(.ivu-col) {
      box-shadow: 1px 0 0 0 #e8eaec, 0 1px 0 0 #e8eaec, 1px 1px 0 0 #e8eaec, inset 1px 0 0 0 #e8eaec, inset 0 1px 0 0 #e8eaec;
      text-align: center;
      padding: 10px 0;
    }
  }

  .time {
    font-size: 14px;
    font-weight: bold;
  }

  .content {
    padding-left: 5px;
    word-wrap: break-word;
  }
}
</style>
